﻿using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Timers;
using System.Configuration;
using QueueManager.Helper;

namespace QueueManager.Service
{
  partial class QueueService : ServiceBase
  {
    private readonly Timer _objTimer = new Timer();
    private readonly QueueSection _objSettings = new QueueSection();
    private readonly QueueMonitor _objMonitor = new QueueMonitor();
    private DateTime _objLastTempQueueRun =  DateTime.MinValue;
    private readonly Dictionary<string, DateTime> _objLastRun = new Dictionary<string, DateTime>();


    public QueueService()
    {
      InitializeComponent();

      _objSettings = (QueueSection)ConfigurationManager.GetSection("queues");

      //Set timer 10 to fire off every 10 seconds
      _objTimer.Elapsed += ObjTimerElapsed;
      _objTimer.Interval = 10000;
      _objTimer.AutoReset = false;
      _objTimer.Start();
    }


    private void ObjTimerElapsed(object sender, ElapsedEventArgs e)
    {
      _objTimer.Stop();

      foreach (QueueSetting objQueue in _objSettings.Queues)
      {
        if (_objLastRun.ContainsKey(objQueue.Name))
        {
          if (DateTime.Now.Subtract(_objLastRun[objQueue.Name]).TotalSeconds > objQueue.Interval)
          {
            _objMonitor.ProcessQueue(objQueue);
            _objLastRun[objQueue.Name] = DateTime.Now;
          }
        }
        else
        {
          _objMonitor.ProcessQueue(objQueue);
          _objLastRun.Add(objQueue.Name, DateTime.Now);
        }
      }

      //Should we process temp queues?
      if (DateTime.Now.Subtract(_objLastTempQueueRun).TotalHours > 1)
      {
        foreach (QueueSetting objQueue in _objSettings.Queues)
        {
          //objMonitor.ProcessTempQueue(objQueue);
        }

        _objLastTempQueueRun = DateTime.Now;
      }

      _objTimer.Start();

    }

   protected override void OnStart(string[] args)
    {
      LogHelper.Log(String.Format("CRM Queue Manager {0} started.", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version), null, LogHelper.LogType.Information);
      _objTimer.Start();
    }

    protected override void OnStop()
    {
      // TODO: Add code here to perform any tear-down necessary to stop your service.
    }
  }
}
